package com.um.jdy.tcp.netty;

import com.um.jdy.tcp.properties.HshNettyProperties;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.json.JsonObjectDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author 邓南辉
 * @date 2020/2/13
 * @copyright 广州优匠科技有限公司
 */
@Component
public class NettyChannelInitializer extends ChannelInitializer<Channel> {

    @Autowired
    NettyChannelHandler nettyChannelHandler;

    @Autowired
    HshNettyProperties hshNettyProperties;

    @Override
    protected void initChannel(Channel channel) {
        ChannelPipeline pipeline = channel.pipeline();
        if (hshNettyProperties.getIdleTimeSeconds() > 0) {
            pipeline.addLast(new IdleStateHandler(hshNettyProperties.getIdleTimeSeconds(), 0, 0));
        }
        pipeline.addLast(new JsonObjectDecoder())
                .addLast(new StringEncoder())
                .addLast(nettyChannelHandler);
    }
}
